* (bug 1805) Initialise $wgContLang before $wgUser
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 /**
3 * See user.txt
4 *
5 * @package MediaWiki
6 */
7
8 /**
9 *
10 */
11 require_once( 'WatchedItem.php' );
12
13 # Number of characters in user_token field
14 define( 'USER_TOKEN_LENGTH', 32 );
15
16 /**
17 *
18 * @package MediaWiki
19 */
20 class User {
21 /**#@+
22 * @access private
23 */
24 var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
25 var $mEmailAuthenticated;
26 var $mRights, $mOptions;
27 var $mDataLoaded, $mNewpassword;
28 var $mSkin;
29 var $mBlockedby, $mBlockreason;
30 var $mTouched;
31 var $mToken;
32 var $mRealName;
33 var $mHash;
34 var $mGroups;
35
36 /** Construct using User:loadDefaults() */
37 function User() {
38 $this->loadDefaults();
39 }
40
41 /**
42 * Static factory method
43 * @param string $name Username, validated by Title:newFromText()
44 * @return User
45 * @static
46 */
47 function newFromName( $name ) {
48 $u = new User();
49
50 # Clean up name according to title rules
51
52 $t = Title::newFromText( $name );
53 if( is_null( $t ) ) {
54 return NULL;
55 } else {
56 $u->setName( $t->getText() );
57 $u->setId( $u->idFromName( $t->getText() ) );
58 return $u;
59 }
60 }
61
62 /**
63 * Factory method to fetch whichever use has a given email confirmation code.
64 * This code is generated when an account is created or its e-mail address
65 * has changed.
66 *
67 * If the code is invalid or has expired, returns NULL.
68 *
69 * @param string $code
70 * @return User
71 * @static
72 */
73 function newFromConfirmationCode( $code ) {
74 $dbr =& wfGetDB( DB_SLAVE );
75 $name = $dbr->selectField( 'user', 'user_name', array(
76 'user_email_token' => md5( $code ),
77 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
78 ) );
79 if( is_string( $name ) ) {
80 return User::newFromName( $name );
81 } else {
82 return null;
83 }
84 }
85
86 /**
87 * Get username given an id.
88 * @param integer $id Database user id
89 * @return string Nickname of a user
90 * @static
91 */
92 function whoIs( $id ) {
93 $dbr =& wfGetDB( DB_SLAVE );
94 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
95 }
96
97 /**
98 * Get real username given an id.
99 * @param integer $id Database user id
100 * @return string Realname of a user
101 * @static
102 */
103 function whoIsReal( $id ) {
104 $dbr =& wfGetDB( DB_SLAVE );
105 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
106 }
107
108 /**
109 * Get database id given a user name
110 * @param string $name Nickname of a user
111 * @return integer|null Database user id (null: if non existent
112 * @static
113 */
114 function idFromName( $name ) {
115 $fname = "User::idFromName";
116
117 $nt = Title::newFromText( $name );
118 if( is_null( $nt ) ) {
119 # Illegal name
120 return null;
121 }
122 $dbr =& wfGetDB( DB_SLAVE );
123 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
124
125 if ( $s === false ) {
126 return 0;
127 } else {
128 return $s->user_id;
129 }
130 }
131
132 /**
133 * does the string match an anonymous IPv4 address?
134 *
135 * @static
136 * @param string $name Nickname of a user
137 * @return bool
138 */
139 function isIP( $name ) {
140 return preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/",$name);
141 /*return preg_match("/^
142 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
143 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
144 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
145 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
146 $/x", $name);*/
147 }
148
149 /**
150 * does the string match roughly an email address ?
151 *
152 * @bug 959
153 *
154 * @param string $addr email address
155 * @static
156 * @return bool
157 */
158 function isValidEmailAddr ( $addr ) {
159 # There used to be a regular expression here, it got removed because it
160 # rejected valid addresses.
161 return ( trim( $addr ) != '' ) &&
162 (false !== strpos( $addr, '@' ) );
163 }
164
165 /**
166 * probably return a random password
167 * @return string probably a random password
168 * @static
169 * @todo Check what is doing really [AV]
170 */
171 function randomPassword() {
172 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
173 $l = strlen( $pwchars ) - 1;
174
175 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
176 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
177 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
178 $pwchars{mt_rand( 0, $l )};
179 return $np;
180 }
181
182 /**
183 * Set properties to default
184 * Used at construction. It will load per language default settings only
185 * if we have an available language object.
186 */
187 function loadDefaults() {
188 static $n=0;
189 $n++;
190 $fname = 'User::loadDefaults' . $n;
191 wfProfileIn( $fname );
192
193 global $wgContLang, $wgIP, $wgDBname;
194 global $wgNamespacesToBeSearchedDefault;
195
196 $this->mId = 0;
197 $this->mNewtalk = -1;
198 $this->mName = $wgIP;
199 $this->mRealName = $this->mEmail = '';
200 $this->mEmailAuthenticated = null;
201 $this->mPassword = $this->mNewpassword = '';
202 $this->mRights = array();
203 $this->mGroups = array();
204 $this->mOptions = User::getDefaultOptions();
205
206 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
207 $this->mOptions['searchNs'.$nsnum] = $val;
208 }
209 unset( $this->mSkin );
210 $this->mDataLoaded = false;
211 $this->mBlockedby = -1; # Unset
212 $this->setToken(); # Random
213 $this->mHash = false;
214
215 if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
216 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgDBname.'LoggedOut'] );
217 }
218 else {
219 $this->mTouched = '0'; # Allow any pages to be cached
220 }
221
222 wfProfileOut( $fname );
223 }
224
225 /**
226 * Combine the language default options with any site-specific options
227 * and add the default language variants.
228 *
229 * @return array
230 * @static
231 * @access private
232 */
233 function getDefaultOptions() {
234 /**
235 * Site defaults will override the global/language defaults
236 */
237 global $wgContLang, $wgDefaultUserOptions;
238 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptions();
239
240 /**
241 * default language setting
242 */
243 $variant = $wgContLang->getPreferredVariant();
244 $defOpt['variant'] = $variant;
245 $defOpt['language'] = $variant;
246
247 return $defOpt;
248 }
249
250 /**
251 * Get a given default option value.
252 *
253 * @param string $opt
254 * @return string
255 * @static
256 * @access public
257 */
258 function getDefaultOption( $opt ) {
259 $defOpts = User::getDefaultOptions();
260 if( isset( $defOpts[$opt] ) ) {
261 return $defOpts[$opt];
262 } else {
263 return '';
264 }
265 }
266
267 /**
268 * Get blocking information
269 * @access private
270 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
271 * non-critical checks are done against slaves. Check when actually saving should be done against
272 * master.
273 *
274 * Note that even if $bFromSlave is false, the check is done first against slave, then master.
275 * The logic is that if blocked on slave, we'll assume it's either blocked on master or
276 * just slightly outta sync and soon corrected - safer to block slightly more that less.
277 * And it's cheaper to check slave first, then master if needed, than master always.
278 */
279 function getBlockedStatus( $bFromSlave = true ) {
280 global $wgIP, $wgBlockCache, $wgProxyList, $wgEnableSorbs, $wgProxyWhitelist;
281
282 if ( -1 != $this->mBlockedby ) { return; }
283
284 $this->mBlockedby = 0;
285
286 # User blocking
287 if ( $this->mId ) {
288 $block = new Block();
289 $block->forUpdate( $bFromSlave );
290 if ( $block->load( $wgIP , $this->mId ) ) {
291 $this->mBlockedby = $block->mBy;
292 $this->mBlockreason = $block->mReason;
293 $this->spreadBlock();
294 }
295 }
296
297 # IP/range blocking
298 if ( !$this->mBlockedby ) {
299 # Check first against slave, and optionally from master.
300 $block = $wgBlockCache->get( $wgIP, true );
301 if ( !$block && !$bFromSlave )
302 {
303 # Not blocked: check against master, to make sure.
304 $wgBlockCache->clearLocal( );
305 $block = $wgBlockCache->get( $wgIP, false );
306 }
307 if ( $block !== false ) {
308 $this->mBlockedby = $block->mBy;
309 $this->mBlockreason = $block->mReason;
310 }
311 }
312
313 # Proxy blocking
314 if ( !$this->isSysop() && !in_array( $wgIP, $wgProxyWhitelist ) ) {
315
316 # Local list
317 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
318 $this->mBlockedby = wfMsg( 'proxyblocker' );
319 $this->mBlockreason = wfMsg( 'proxyblockreason' );
320 }
321
322 # DNSBL
323 if ( !$this->mBlockedby && $wgEnableSorbs ) {
324 if ( $this->inSorbsBlacklist( $wgIP ) ) {
325 $this->mBlockedby = wfMsg( 'sorbs' );
326 $this->mBlockreason = wfMsg( 'sorbsreason' );
327 }
328 }
329 }
330 }
331
332 function inSorbsBlacklist( $ip ) {
333 global $wgEnableSorbs;
334 return $wgEnableSorbs &&
335 $this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
336 }
337
338 function inOpmBlacklist( $ip ) {
339 global $wgEnableOpm;
340 return $wgEnableOpm &&
341 $this->inDnsBlacklist( $ip, 'opm.blitzed.org.' );
342 }
343
344 function inDnsBlacklist( $ip, $base ) {
345 $fname = 'User::inDnsBlacklist';
346 wfProfileIn( $fname );
347
348 $found = false;
349 $host = '';
350
351 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
352 # Make hostname
353 for ( $i=4; $i>=1; $i-- ) {
354 $host .= $m[$i] . '.';
355 }
356 $host .= $base;
357
358 # Send query
359 $ipList = gethostbynamel( $host );
360
361 if ( $ipList ) {
362 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
363 $found = true;
364 } else {
365 wfDebug( "Requested $host, not found in $base.\n" );
366 }
367 }
368
369 wfProfileOut( $fname );
370 return $found;
371 }
372
373 /**
374 * Primitive rate limits: enforce maximum actions per time period
375 * to put a brake on flooding.
376 *
377 * Note: when using a shared cache like memcached, IP-address
378 * last-hit counters will be shared across wikis.
379 *
380 * @return bool true if a rate limiter was tripped
381 * @access public
382 */
383 function pingLimiter( $action='edit' ) {
384 global $wgRateLimits;
385 if( !isset( $wgRateLimits[$action] ) ) {
386 return false;
387 }
388 if( $this->isAllowed( 'delete' ) ) {
389 // goddam cabal
390 return false;
391 }
392
393 global $wgMemc, $wgIP, $wgDBname, $wgRateLimitLog;
394 $fname = 'User::pingLimiter';
395 $limits = $wgRateLimits[$action];
396 $keys = array();
397 $id = $this->getId();
398
399 if( isset( $limits['anon'] ) && $id == 0 ) {
400 $keys["$wgDBname:limiter:$action:anon"] = $limits['anon'];
401 }
402
403 if( isset( $limits['user'] ) && $id != 0 ) {
404 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['user'];
405 }
406 if( $this->isNewbie() ) {
407 if( isset( $limits['newbie'] ) && $id != 0 ) {
408 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['newbie'];
409 }
410 if( isset( $limits['ip'] ) ) {
411 $keys["mediawiki:limiter:$action:ip:$wgIP"] = $limits['ip'];
412 }
413 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $wgIP, $matches ) ) {
414 $subnet = $matches[1];
415 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
416 }
417 }
418
419 $triggered = false;
420 foreach( $keys as $key => $limit ) {
421 list( $max, $period ) = $limit;
422 $summary = "(limit $max in {$period}s)";
423 $count = $wgMemc->get( $key );
424 if( $count ) {
425 if( $count > $max ) {
426 wfDebug( "$fname: tripped! $key at $count $summary\n" );
427 if( $wgRateLimitLog ) {
428 @error_log( wfTimestamp( TS_MW ) . ' ' . $wgDBname . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
429 }
430 $triggered = true;
431 } else {
432 wfDebug( "$fname: ok. $key at $count $summary\n" );
433 }
434 } else {
435 wfDebug( "$fname: adding record for $key $summary\n" );
436 $wgMemc->add( $key, 1, IntVal( $period ) );
437 }
438 $wgMemc->incr( $key );
439 }
440
441 return $triggered;
442 }
443
444 /**
445 * Check if user is blocked
446 * @return bool True if blocked, false otherwise
447 */
448 function isBlocked( $bFromSlave = false ) {
449 $this->getBlockedStatus( $bFromSlave );
450 return $this->mBlockedby !== 0;
451 }
452
453 /**
454 * Get name of blocker
455 * @return string name of blocker
456 */
457 function blockedBy() {
458 $this->getBlockedStatus();
459 return $this->mBlockedby;
460 }
461
462 /**
463 * Get blocking reason
464 * @return string Blocking reason
465 */
466 function blockedFor() {
467 $this->getBlockedStatus();
468 return $this->mBlockreason;
469 }
470
471 /**
472 * Initialise php session
473 */
474 function SetupSession() {
475 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
476 if( $wgSessionsInMemcached ) {
477 require_once( 'MemcachedSessions.php' );
478 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
479 # If it's left on 'user' or another setting from another
480 # application, it will end up failing. Try to recover.
481 ini_set ( 'session.save_handler', 'files' );
482 }
483 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
484 session_cache_limiter( 'private, must-revalidate' );
485 @session_start();
486 }
487
488 /**
489 * Read datas from session
490 * @static
491 */
492 function loadFromSession() {
493 global $wgMemc, $wgDBname;
494
495 if ( isset( $_SESSION['wsUserID'] ) ) {
496 if ( 0 != $_SESSION['wsUserID'] ) {
497 $sId = $_SESSION['wsUserID'];
498 } else {
499 return new User();
500 }
501 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
502 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
503 $_SESSION['wsUserID'] = $sId;
504 } else {
505 return new User();
506 }
507 if ( isset( $_SESSION['wsUserName'] ) ) {
508 $sName = $_SESSION['wsUserName'];
509 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
510 $sName = $_COOKIE["{$wgDBname}UserName"];
511 $_SESSION['wsUserName'] = $sName;
512 } else {
513 return new User();
514 }
515
516 $passwordCorrect = FALSE;
517 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
518 if($makenew = !$user) {
519 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
520 $user = new User();
521 $user->mId = $sId;
522 $user->loadFromDatabase();
523 } else {
524 wfDebug( "User::loadFromSession() got from cache!\n" );
525 }
526
527 if ( isset( $_SESSION['wsToken'] ) ) {
528 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken;
529 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
530 $passwordCorrect = $user->mToken == $_COOKIE["{$wgDBname}Token"];
531 } else {
532 return new User(); # Can't log in from session
533 }
534
535 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
536 if($makenew) {
537 if($wgMemc->set( $key, $user ))
538 wfDebug( "User::loadFromSession() successfully saved user\n" );
539 else
540 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
541 }
542 return $user;
543 }
544 return new User(); # Can't log in from session
545 }
546
547 /**
548 * Load a user from the database
549 */
550 function loadFromDatabase() {
551 global $wgCommandLineMode;
552 $fname = "User::loadFromDatabase";
553
554 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
555 # loading in a command line script, don't assume all command line scripts need it like this
556 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
557 if ( $this->mDataLoaded ) {
558 return;
559 }
560
561 # Paranoia
562 $this->mId = IntVal( $this->mId );
563
564 /** Anonymous user */
565 if( !$this->mId ) {
566 /** Get rights */
567 $this->mRights = $this->getGroupPermissions( array( '*' ) );
568 $this->mDataLoaded = true;
569 return;
570 } # the following stuff is for non-anonymous users only
571
572 $dbr =& wfGetDB( DB_SLAVE );
573 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
574 'user_email_authenticated',
575 'user_real_name','user_options','user_touched', 'user_token' ),
576 array( 'user_id' => $this->mId ), $fname );
577
578 if ( $s !== false ) {
579 $this->mName = $s->user_name;
580 $this->mEmail = $s->user_email;
581 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $s->user_email_authenticated );
582 $this->mRealName = $s->user_real_name;
583 $this->mPassword = $s->user_password;
584 $this->mNewpassword = $s->user_newpassword;
585 $this->decodeOptions( $s->user_options );
586 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
587 $this->mToken = $s->user_token;
588
589 $res = $dbr->select( 'user_groups',
590 array( 'ug_group' ),
591 array( 'ug_user' => $this->mId ),
592 $fname );
593 $this->mGroups = array();
594 while( $row = $dbr->fetchObject( $res ) ) {
595 $this->mGroups[] = $row->ug_group;
596 }
597 $effectiveGroups = array_merge( array( '*', 'user' ), $this->mGroups );
598 $this->mRights = $this->getGroupPermissions( $effectiveGroups );
599 }
600
601 $this->mDataLoaded = true;
602 }
603
604 function getID() { return $this->mId; }
605 function setID( $v ) {
606 $this->mId = $v;
607 $this->mDataLoaded = false;
608 }
609
610 function getName() {
611 $this->loadFromDatabase();
612 return $this->mName;
613 }
614
615 function setName( $str ) {
616 $this->loadFromDatabase();
617 $this->mName = $str;
618 }
619
620
621 /**
622 * Return the title dbkey form of the name, for eg user pages.
623 * @return string
624 * @access public
625 */
626 function getTitleKey() {
627 return str_replace( ' ', '_', $this->getName() );
628 }
629
630 function getNewtalk() {
631 $fname = 'User::getNewtalk';
632 $this->loadFromDatabase();
633
634 # Load the newtalk status if it is unloaded (mNewtalk=-1)
635 if( $this->mNewtalk == -1 ) {
636 $this->mNewtalk = 0; # reset talk page status
637
638 # Check memcached separately for anons, who have no
639 # entire User object stored in there.
640 if( !$this->mId ) {
641 global $wgDBname, $wgMemc;
642 $key = "$wgDBname:newtalk:ip:{$this->mName}";
643 $newtalk = $wgMemc->get( $key );
644 if( is_integer( $newtalk ) ) {
645 $this->mNewtalk = $newtalk ? 1 : 0;
646 return (bool)$this->mNewtalk;
647 }
648 }
649
650 $dbr =& wfGetDB( DB_SLAVE );
651 $res = $dbr->select( 'watchlist',
652 array( 'wl_user' ),
653 array( 'wl_title' => $this->getTitleKey(),
654 'wl_namespace' => NS_USER_TALK,
655 'wl_user' => $this->mId,
656 'wl_notificationtimestamp != 0' ),
657 'User::getNewtalk' );
658 if( $dbr->numRows($res) > 0 ) {
659 $this->mNewtalk = 1;
660 }
661 $dbr->freeResult( $res );
662
663 if( !$this->mId ) {
664 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
665 }
666 }
667
668 return ( 0 != $this->mNewtalk );
669 }
670
671 function setNewtalk( $val ) {
672 $this->loadFromDatabase();
673 $this->mNewtalk = $val;
674 $this->invalidateCache();
675 }
676
677 function invalidateCache() {
678 global $wgClockSkewFudge;
679 $this->loadFromDatabase();
680 $this->mTouched = wfTimestamp(TS_MW, time() + $wgClockSkewFudge );
681 # Don't forget to save the options after this or
682 # it won't take effect!
683 }
684
685 function validateCache( $timestamp ) {
686 $this->loadFromDatabase();
687 return ($timestamp >= $this->mTouched);
688 }
689
690 /**
691 * Salt a password.
692 * Will only be salted if $wgPasswordSalt is true
693 * @param string Password.
694 * @return string Salted password or clear password.
695 */
696 function addSalt( $p ) {
697 global $wgPasswordSalt;
698 if($wgPasswordSalt)
699 return md5( "{$this->mId}-{$p}" );
700 else
701 return $p;
702 }
703
704 /**
705 * Encrypt a password.
706 * It can eventuall salt a password @see User::addSalt()
707 * @param string $p clear Password.
708 * @param string Encrypted password.
709 */
710 function encryptPassword( $p ) {
711 return $this->addSalt( md5( $p ) );
712 }
713
714 # Set the password and reset the random token
715 function setPassword( $str ) {
716 $this->loadFromDatabase();
717 $this->setToken();
718 $this->mPassword = $this->encryptPassword( $str );
719 $this->mNewpassword = '';
720 }
721
722 # Set the random token (used for persistent authentication)
723 function setToken( $token = false ) {
724 global $wgSecretKey, $wgProxyKey, $wgDBname;
725 if ( !$token ) {
726 if ( $wgSecretKey ) {
727 $key = $wgSecretKey;
728 } elseif ( $wgProxyKey ) {
729 $key = $wgProxyKey;
730 } else {
731 $key = microtime();
732 }
733 $this->mToken = md5( $wgSecretKey . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId );
734 } else {
735 $this->mToken = $token;
736 }
737 }
738
739
740 function setCookiePassword( $str ) {
741 $this->loadFromDatabase();
742 $this->mCookiePassword = md5( $str );
743 }
744
745 function setNewpassword( $str ) {
746 $this->loadFromDatabase();
747 $this->mNewpassword = $this->encryptPassword( $str );
748 }
749
750 function getEmail() {
751 $this->loadFromDatabase();
752 return $this->mEmail;
753 }
754
755 function getEmailAuthenticationTimestamp() {
756 $this->loadFromDatabase();
757 return $this->mEmailAuthenticated;
758 }
759
760 function setEmail( $str ) {
761 $this->loadFromDatabase();
762 $this->mEmail = $str;
763 }
764
765 function getRealName() {
766 $this->loadFromDatabase();
767 return $this->mRealName;
768 }
769
770 function setRealName( $str ) {
771 $this->loadFromDatabase();
772 $this->mRealName = $str;
773 }
774
775 function getOption( $oname ) {
776 $this->loadFromDatabase();
777 if ( array_key_exists( $oname, $this->mOptions ) ) {
778 return $this->mOptions[$oname];
779 } else {
780 return '';
781 }
782 }
783
784 function setOption( $oname, $val ) {
785 $this->loadFromDatabase();
786 if ( $oname == 'skin' ) {
787 # Clear cached skin, so the new one displays immediately in Special:Preferences
788 unset( $this->mSkin );
789 }
790 $this->mOptions[$oname] = $val;
791 $this->invalidateCache();
792 }
793
794 function getRights() {
795 $this->loadFromDatabase();
796 return $this->mRights;
797 }
798
799 /**
800 * Get the list of explicit group memberships this user has.
801 * The implicit * and user groups are not included.
802 * @return array of strings
803 */
804 function getGroups() {
805 $this->loadFromDatabase();
806 return $this->mGroups;
807 }
808
809 /**
810 * Get the list of implicit group memberships this user has.
811 * This includes all explicit groups, plus 'user' if logged in
812 * and '*' for all accounts.
813 * @return array of strings
814 */
815 function getEffectiveGroups() {
816 $base = array( '*' );
817 if( $this->isLoggedIn() ) {
818 $base[] = 'user';
819 }
820 return array_merge( $base, $this->getGroups() );
821 }
822
823 /**
824 * Remove the user from the given group.
825 * This takes immediate effect.
826 * @string $group
827 */
828 function addGroup( $group ) {
829 $dbw =& wfGetDB( DB_MASTER );
830 $dbw->insert( 'user_groups',
831 array(
832 'ug_user' => $this->getID(),
833 'ug_group' => $group,
834 ),
835 'User::addGroup',
836 array( 'IGNORE' ) );
837
838 $this->mGroups = array_merge( $this->mGroups, array( $group ) );
839 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups() );
840
841 $this->invalidateCache();
842 $this->saveSettings();
843 }
844
845 /**
846 * Remove the user from the given group.
847 * This takes immediate effect.
848 * @string $group
849 */
850 function removeGroup( $group ) {
851 $dbw =& wfGetDB( DB_MASTER );
852 $dbw->delete( 'user_groups',
853 array(
854 'ug_user' => $this->getID(),
855 'ug_group' => $group,
856 ),
857 'User::removeGroup' );
858
859 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
860 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups() );
861
862 $this->invalidateCache();
863 $this->saveSettings();
864 }
865
866
867 /**
868 * A more legible check for non-anonymousness.
869 * Returns true if the user is not an anonymous visitor.
870 *
871 * @return bool
872 */
873 function isLoggedIn() {
874 return( $this->getID() != 0 );
875 }
876
877 /**
878 * A more legible check for anonymousness.
879 * Returns true if the user is an anonymous visitor.
880 *
881 * @return bool
882 */
883 function isAnon() {
884 return !$this->isLoggedIn();
885 }
886
887 /**
888 * Check if a user is sysop
889 * Die with backtrace. Use User:isAllowed() instead.
890 * @deprecated
891 */
892 function isSysop() {
893 return $this->isAllowed( 'protect' );
894 }
895
896 /** @deprecated */
897 function isDeveloper() {
898 return $this->isAllowed( 'siteadmin' );
899 }
900
901 /** @deprecated */
902 function isBureaucrat() {
903 return $this->isAllowed( 'makesysop' );
904 }
905
906 /**
907 * Whether the user is a bot
908 * @todo need to be migrated to the new user level management sytem
909 */
910 function isBot() {
911 $this->loadFromDatabase();
912 return in_array( 'bot', $this->mRights );
913 }
914
915 /**
916 * Check if user is allowed to access a feature / make an action
917 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
918 * @return boolean True: action is allowed, False: action should not be allowed
919 */
920 function isAllowed($action='') {
921 $this->loadFromDatabase();
922 return in_array( $action , $this->mRights );
923 }
924
925 /**
926 * Load a skin if it doesn't exist or return it
927 * @todo FIXME : need to check the old failback system [AV]
928 */
929 function &getSkin() {
930 global $IP;
931 if ( ! isset( $this->mSkin ) ) {
932 $fname = 'User::getSkin';
933 wfProfileIn( $fname );
934
935 # get all skin names available
936 $skinNames = Skin::getSkinNames();
937
938 # get the user skin
939 $userSkin = $this->getOption( 'skin' );
940 if ( $userSkin == '' ) { $userSkin = 'standard'; }
941
942 if ( !isset( $skinNames[$userSkin] ) ) {
943 # in case the user skin could not be found find a replacement
944 $fallback = array(
945 0 => 'Standard',
946 1 => 'Nostalgia',
947 2 => 'CologneBlue');
948 # if phptal is enabled we should have monobook skin that
949 # superseed the good old SkinStandard.
950 if ( isset( $skinNames['monobook'] ) ) {
951 $fallback[0] = 'MonoBook';
952 }
953
954 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
955 $sn = $fallback[$userSkin];
956 } else {
957 $sn = 'Standard';
958 }
959 } else {
960 # The user skin is available
961 $sn = $skinNames[$userSkin];
962 }
963
964 # Grab the skin class and initialise it. Each skin checks for PHPTal
965 # and will not load if it's not enabled.
966 require_once( $IP.'/skins/'.$sn.'.php' );
967
968 # Check if we got if not failback to default skin
969 $className = 'Skin'.$sn;
970 if( !class_exists( $className ) ) {
971 # DO NOT die if the class isn't found. This breaks maintenance
972 # scripts and can cause a user account to be unrecoverable
973 # except by SQL manipulation if a previously valid skin name
974 # is no longer valid.
975 $className = 'SkinStandard';
976 require_once( $IP.'/skins/Standard.php' );
977 }
978 $this->mSkin =& new $className;
979 wfProfileOut( $fname );
980 }
981 return $this->mSkin;
982 }
983
984 /**#@+
985 * @param string $title Article title to look at
986 */
987
988 /**
989 * Check watched status of an article
990 * @return bool True if article is watched
991 */
992 function isWatched( $title ) {
993 $wl = WatchedItem::fromUserTitle( $this, $title );
994 return $wl->isWatched();
995 }
996
997 /**
998 * Watch an article
999 */
1000 function addWatch( $title ) {
1001 $wl = WatchedItem::fromUserTitle( $this, $title );
1002 $wl->addWatch();
1003 $this->invalidateCache();
1004 }
1005
1006 /**
1007 * Stop watching an article
1008 */
1009 function removeWatch( $title ) {
1010 $wl = WatchedItem::fromUserTitle( $this, $title );
1011 $wl->removeWatch();
1012 $this->invalidateCache();
1013 }
1014
1015 /**
1016 * Clear the user's notification timestamp for the given title.
1017 * If e-notif e-mails are on, they will receive notification mails on
1018 * the next change of the page if it's watched etc.
1019 */
1020 function clearNotification( &$title ) {
1021 global $wgUser;
1022
1023 $userid = $this->getID();
1024 if ($userid==0)
1025 return;
1026
1027 // Only update the timestamp if the page is being watched.
1028 // The query to find out if it is watched is cached both in memcached and per-invocation,
1029 // and when it does have to be executed, it can be on a slave
1030 // If this is the user's newtalk page, we always update the timestamp
1031 if ($title->getNamespace() == NS_USER_TALK &&
1032 $title->getText() == $wgUser->getName())
1033 {
1034 $watched = true;
1035 } elseif ( $this->getID() == $wgUser->getID() ) {
1036 $watched = $title->userIsWatching();
1037 } else {
1038 $watched = true;
1039 }
1040
1041 // If the page is watched by the user (or may be watched), update the timestamp on any
1042 // any matching rows
1043 if ( $watched ) {
1044 $dbw =& wfGetDB( DB_MASTER );
1045 $success = $dbw->update( 'watchlist',
1046 array( /* SET */
1047 'wl_notificationtimestamp' => 0
1048 ), array( /* WHERE */
1049 'wl_title' => $title->getDBkey(),
1050 'wl_namespace' => $title->getNamespace(),
1051 'wl_user' => $this->getID()
1052 ), 'User::clearLastVisited'
1053 );
1054 }
1055 }
1056
1057 /**#@-*/
1058
1059 /**
1060 * Resets all of the given user's page-change notification timestamps.
1061 * If e-notif e-mails are on, they will receive notification mails on
1062 * the next change of any watched page.
1063 *
1064 * @param int $currentUser user ID number
1065 * @access public
1066 */
1067 function clearAllNotifications( $currentUser ) {
1068 if( $currentUser != 0 ) {
1069
1070 $dbw =& wfGetDB( DB_MASTER );
1071 $success = $dbw->update( 'watchlist',
1072 array( /* SET */
1073 'wl_notificationtimestamp' => 0
1074 ), array( /* WHERE */
1075 'wl_user' => $currentUser
1076 ), 'UserMailer::clearAll'
1077 );
1078
1079 # we also need to clear here the "you have new message" notification for the own user_talk page
1080 # This is cleared one page view later in Article::viewUpdates();
1081 }
1082 }
1083
1084 /**
1085 * @access private
1086 * @return string Encoding options
1087 */
1088 function encodeOptions() {
1089 $a = array();
1090 foreach ( $this->mOptions as $oname => $oval ) {
1091 array_push( $a, $oname.'='.$oval );
1092 }
1093 $s = implode( "\n", $a );
1094 return $s;
1095 }
1096
1097 /**
1098 * @access private
1099 */
1100 function decodeOptions( $str ) {
1101 $a = explode( "\n", $str );
1102 foreach ( $a as $s ) {
1103 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1104 $this->mOptions[$m[1]] = $m[2];
1105 }
1106 }
1107 }
1108
1109 function setCookies() {
1110 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
1111 if ( 0 == $this->mId ) return;
1112 $this->loadFromDatabase();
1113 $exp = time() + $wgCookieExpiration;
1114
1115 $_SESSION['wsUserID'] = $this->mId;
1116 setcookie( $wgDBname.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
1117
1118 $_SESSION['wsUserName'] = $this->mName;
1119 setcookie( $wgDBname.'UserName', $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
1120
1121 $_SESSION['wsToken'] = $this->mToken;
1122 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1123 setcookie( $wgDBname.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain );
1124 } else {
1125 setcookie( $wgDBname.'Token', '', time() - 3600 );
1126 }
1127 }
1128
1129 /**
1130 * Logout user
1131 * It will clean the session cookie
1132 */
1133 function logout() {
1134 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
1135 $this->loadDefaults();
1136 $this->setLoaded( true );
1137
1138 $_SESSION['wsUserID'] = 0;
1139
1140 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1141 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1142
1143 # Remember when user logged out, to prevent seeing cached pages
1144 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain );
1145 }
1146
1147 /**
1148 * Save object settings into database
1149 */
1150 function saveSettings() {
1151 global $wgMemc, $wgDBname;
1152 $fname = 'User::saveSettings';
1153
1154 $dbw =& wfGetDB( DB_MASTER );
1155 if ( ! $this->getNewtalk() ) {
1156 # Delete the watchlist entry for user_talk page X watched by user X
1157 $dbw->delete( 'watchlist',
1158 array( 'wl_user' => $this->mId,
1159 'wl_title' => $this->getTitleKey(),
1160 'wl_namespace' => NS_USER_TALK ),
1161 $fname );
1162 if( !$this->mId ) {
1163 # Anon users have a separate memcache space for newtalk
1164 # since they don't store their own info. Trim...
1165 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1166 }
1167 }
1168
1169 if ( 0 == $this->mId ) { return; }
1170
1171 $dbw->update( 'user',
1172 array( /* SET */
1173 'user_name' => $this->mName,
1174 'user_password' => $this->mPassword,
1175 'user_newpassword' => $this->mNewpassword,
1176 'user_real_name' => $this->mRealName,
1177 'user_email' => $this->mEmail,
1178 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1179 'user_options' => $this->encodeOptions(),
1180 'user_touched' => $dbw->timestamp($this->mTouched),
1181 'user_token' => $this->mToken
1182 ), array( /* WHERE */
1183 'user_id' => $this->mId
1184 ), $fname
1185 );
1186 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1187 }
1188
1189 /**
1190 * Checks if a user with the given name exists, returns the ID
1191 */
1192 function idForName() {
1193 $fname = 'User::idForName';
1194
1195 $gotid = 0;
1196 $s = trim( $this->mName );
1197 if ( 0 == strcmp( '', $s ) ) return 0;
1198
1199 $dbr =& wfGetDB( DB_SLAVE );
1200 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1201 if ( $id === false ) {
1202 $id = 0;
1203 }
1204 return $id;
1205 }
1206
1207 /**
1208 * Add user object to the database
1209 */
1210 function addToDatabase() {
1211 $fname = 'User::addToDatabase';
1212 $dbw =& wfGetDB( DB_MASTER );
1213 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1214 $dbw->insert( 'user',
1215 array(
1216 'user_id' => $seqVal,
1217 'user_name' => $this->mName,
1218 'user_password' => $this->mPassword,
1219 'user_newpassword' => $this->mNewpassword,
1220 'user_email' => $this->mEmail,
1221 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1222 'user_real_name' => $this->mRealName,
1223 'user_options' => $this->encodeOptions(),
1224 'user_token' => $this->mToken
1225 ), $fname
1226 );
1227 $this->mId = $dbw->insertId();
1228 }
1229
1230 function spreadBlock() {
1231 global $wgIP;
1232 # If the (non-anonymous) user is blocked, this function will block any IP address
1233 # that they successfully log on from.
1234 $fname = 'User::spreadBlock';
1235
1236 wfDebug( "User:spreadBlock()\n" );
1237 if ( $this->mId == 0 ) {
1238 return;
1239 }
1240
1241 $userblock = Block::newFromDB( '', $this->mId );
1242 if ( !$userblock->isValid() ) {
1243 return;
1244 }
1245
1246 # Check if this IP address is already blocked
1247 $ipblock = Block::newFromDB( $wgIP );
1248 if ( $ipblock->isValid() ) {
1249 # Just update the timestamp
1250 $ipblock->updateTimestamp();
1251 return;
1252 }
1253
1254 # Make a new block object with the desired properties
1255 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1256 $ipblock->mAddress = $wgIP;
1257 $ipblock->mUser = 0;
1258 $ipblock->mBy = $userblock->mBy;
1259 $ipblock->mReason = wfMsg( 'autoblocker', $this->getName(), $userblock->mReason );
1260 $ipblock->mTimestamp = wfTimestampNow();
1261 $ipblock->mAuto = 1;
1262 # If the user is already blocked with an expiry date, we don't
1263 # want to pile on top of that!
1264 if($userblock->mExpiry) {
1265 $ipblock->mExpiry = min ( $userblock->mExpiry, Block::getAutoblockExpiry( $ipblock->mTimestamp ));
1266 } else {
1267 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
1268 }
1269
1270 # Insert it
1271 $ipblock->insert();
1272
1273 }
1274
1275 function getPageRenderingHash() {
1276 global $wgContLang;
1277 if( $this->mHash ){
1278 return $this->mHash;
1279 }
1280
1281 // stubthreshold is only included below for completeness,
1282 // it will always be 0 when this function is called by parsercache.
1283
1284 $confstr = $this->getOption( 'math' );
1285 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1286 $confstr .= '!' . $this->getOption( 'editsection' );
1287 $confstr .= '!' . $this->getOption( 'date' );
1288 $confstr .= '!' . $this->getOption( 'numberheadings' );
1289 $confstr .= '!' . $this->getOption( 'language' );
1290 $confstr .= '!' . $this->getOption( 'thumbsize' );
1291 // add in language specific options, if any
1292 $extra = $wgContLang->getExtraHashOptions();
1293 $confstr .= $extra;
1294
1295 $this->mHash = $confstr;
1296 return $confstr ;
1297 }
1298
1299 function isAllowedToCreateAccount() {
1300 return $this->isAllowed( 'createaccount' );
1301 }
1302
1303 /**
1304 * Set mDataLoaded, return previous value
1305 * Use this to prevent DB access in command-line scripts or similar situations
1306 */
1307 function setLoaded( $loaded ) {
1308 return wfSetVar( $this->mDataLoaded, $loaded );
1309 }
1310
1311 /**
1312 * Get this user's personal page title.
1313 *
1314 * @return Title
1315 * @access public
1316 */
1317 function getUserPage() {
1318 return Title::makeTitle( NS_USER, $this->mName );
1319 }
1320
1321 /**
1322 * Get this user's talk page title.
1323 *
1324 * @return Title
1325 * @access public
1326 */
1327 function getTalkPage() {
1328 $title = $this->getUserPage();
1329 return $title->getTalkPage();
1330 }
1331
1332 /**
1333 * @static
1334 */
1335 function getMaxID() {
1336 $dbr =& wfGetDB( DB_SLAVE );
1337 return $dbr->selectField( 'user', 'max(user_id)', false );
1338 }
1339
1340 /**
1341 * Determine whether the user is a newbie. Newbies are either
1342 * anonymous IPs, or the 1% most recently created accounts.
1343 * Bots and sysops are excluded.
1344 * @return bool True if it is a newbie.
1345 */
1346 function isNewbie() {
1347 return $this->isAnon() || $this->mId > User::getMaxID() * 0.99 && !$this->isAllowed( 'delete' ) && !$this->isBot();
1348 }
1349
1350 /**
1351 * Check to see if the given clear-text password is one of the accepted passwords
1352 * @param string $password User password.
1353 * @return bool True if the given password is correct otherwise False.
1354 */
1355 function checkPassword( $password ) {
1356 global $wgAuth, $wgMinimalPasswordLength;
1357 $this->loadFromDatabase();
1358
1359 // Even though we stop people from creating passwords that
1360 // are shorter than this, doesn't mean people wont be able
1361 // to. Certain authentication plugins do NOT want to save
1362 // domain passwords in a mysql database, so we should
1363 // check this (incase $wgAuth->strict() is false).
1364 if( strlen( $password ) < $wgMinimalPasswordLength ) {
1365 return false;
1366 }
1367
1368 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1369 return true;
1370 } elseif( $wgAuth->strict() ) {
1371 /* Auth plugin doesn't allow local authentication */
1372 return false;
1373 }
1374 $ep = $this->encryptPassword( $password );
1375 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
1376 return true;
1377 } elseif ( ($this->mNewpassword != '') && (0 == strcmp( $ep, $this->mNewpassword )) ) {
1378 return true;
1379 } elseif ( function_exists( 'iconv' ) ) {
1380 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1381 # Check for this with iconv
1382 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1383 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
1384 return true;
1385 }
1386 }
1387 return false;
1388 }
1389
1390 /**
1391 * Initialize (if necessary) and return a session token value
1392 * which can be used in edit forms to show that the user's
1393 * login credentials aren't being hijacked with a foreign form
1394 * submission.
1395 *
1396 * @param mixed $salt - Optional function-specific data for hash.
1397 * Use a string or an array of strings.
1398 * @return string
1399 * @access public
1400 */
1401 function editToken( $salt = '' ) {
1402 if( !isset( $_SESSION['wsEditToken'] ) ) {
1403 $token = $this->generateToken();
1404 $_SESSION['wsEditToken'] = $token;
1405 } else {
1406 $token = $_SESSION['wsEditToken'];
1407 }
1408 if( is_array( $salt ) ) {
1409 $salt = implode( '|', $salt );
1410 }
1411 return md5( $token . $salt );
1412 }
1413
1414 /**
1415 * Generate a hex-y looking random token for various uses.
1416 * Could be made more cryptographically sure if someone cares.
1417 * @return string
1418 */
1419 function generateToken( $salt = '' ) {
1420 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1421 return md5( $token . $salt );
1422 }
1423
1424 /**
1425 * Check given value against the token value stored in the session.
1426 * A match should confirm that the form was submitted from the
1427 * user's own login session, not a form submission from a third-party
1428 * site.
1429 *
1430 * @param string $val - the input value to compare
1431 * @param string $salt - Optional function-specific data for hash
1432 * @return bool
1433 * @access public
1434 */
1435 function matchEditToken( $val, $salt = '' ) {
1436 return ( $val == $this->editToken( $salt ) );
1437 }
1438
1439 /**
1440 * Generate a new e-mail confirmation token and send a confirmation
1441 * mail to the user's given address.
1442 *
1443 * @return mixed True on success, a WikiError object on failure.
1444 */
1445 function sendConfirmationMail() {
1446 global $wgIP, $wgContLang;
1447 $url = $this->confirmationTokenUrl( $expiration );
1448 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1449 wfMsg( 'confirmemail_body',
1450 $wgIP,
1451 $this->getName(),
1452 $url,
1453 $wgContLang->timeanddate( $expiration, false ) ) );
1454 }
1455
1456 /**
1457 * Send an e-mail to this user's account. Does not check for
1458 * confirmed status or validity.
1459 *
1460 * @param string $subject
1461 * @param string $body
1462 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1463 * @return mixed True on success, a WikiError object on failure.
1464 */
1465 function sendMail( $subject, $body, $from = null ) {
1466 if( is_null( $from ) ) {
1467 global $wgPasswordSender;
1468 $from = $wgPasswordSender;
1469 }
1470
1471 require_once( 'UserMailer.php' );
1472 $error = userMailer( $this->getEmail(), $from, $subject, $body );
1473
1474 if( $error == '' ) {
1475 return true;
1476 } else {
1477 return new WikiError( $error );
1478 }
1479 }
1480
1481 /**
1482 * Generate, store, and return a new e-mail confirmation code.
1483 * A hash (unsalted since it's used as a key) is stored.
1484 * @param &$expiration mixed output: accepts the expiration time
1485 * @return string
1486 * @access private
1487 */
1488 function confirmationToken( &$expiration ) {
1489 $fname = 'User::confirmationToken';
1490
1491 $now = time();
1492 $expires = $now + 7 * 24 * 60 * 60;
1493 $expiration = wfTimestamp( TS_MW, $expires );
1494
1495 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
1496 $hash = md5( $token );
1497
1498 $dbw =& wfGetDB( DB_MASTER );
1499 $dbw->update( 'user',
1500 array( 'user_email_token' => $hash,
1501 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1502 array( 'user_id' => $this->mId ),
1503 $fname );
1504
1505 return $token;
1506 }
1507
1508 /**
1509 * Generate and store a new e-mail confirmation token, and return
1510 * the URL the user can use to confirm.
1511 * @param &$expiration mixed output: accepts the expiration time
1512 * @return string
1513 * @access private
1514 */
1515 function confirmationTokenUrl( &$expiration ) {
1516 $token = $this->confirmationToken( $expiration );
1517 $title = Title::makeTitle( NS_SPECIAL, 'Confirmemail/' . $token );
1518 return $title->getFullUrl();
1519 }
1520
1521 /**
1522 * Mark the e-mail address confirmed and save.
1523 */
1524 function confirmEmail() {
1525 $this->loadFromDatabase();
1526 $this->mEmailAuthenticated = wfTimestampNow();
1527 $this->saveSettings();
1528 return true;
1529 }
1530
1531 /**
1532 * Is this user allowed to send e-mails within limits of current
1533 * site configuration?
1534 * @return bool
1535 */
1536 function canSendEmail() {
1537 return $this->isEmailConfirmed();
1538 }
1539
1540 /**
1541 * Is this user allowed to receive e-mails within limits of current
1542 * site configuration?
1543 * @return bool
1544 */
1545 function canReceiveEmail() {
1546 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1547 }
1548
1549 /**
1550 * Is this user's e-mail address valid-looking and confirmed within
1551 * limits of the current site configuration?
1552 *
1553 * If $wgEmailAuthentication is on, this may require the user to have
1554 * confirmed their address by returning a code or using a password
1555 * sent to the address from the wiki.
1556 *
1557 * @return bool
1558 */
1559 function isEmailConfirmed() {
1560 global $wgEmailAuthentication;
1561 $this->loadFromDatabase();
1562 if( $this->isAnon() )
1563 return false;
1564 if( !$this->isValidEmailAddr( $this->mEmail ) )
1565 return false;
1566 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
1567 return false;
1568 return true;
1569 }
1570
1571 /**
1572 * @param array $groups list of groups
1573 * @return array list of permission key names for given groups combined
1574 * @static
1575 */
1576 function getGroupPermissions( $groups ) {
1577 global $wgGroupPermissions;
1578 $rights = array();
1579 foreach( $groups as $group ) {
1580 if( isset( $wgGroupPermissions[$group] ) ) {
1581 $rights = array_merge( $rights, $wgGroupPermissions[$group] );
1582 }
1583 }
1584 return $rights;
1585 }
1586
1587 /**
1588 * @param string $group key name
1589 * @return string localized descriptive name, if provided
1590 * @static
1591 */
1592 function getGroupName( $group ) {
1593 $key = "group-$group-name";
1594 $name = wfMsg( $key );
1595 if( $name == '' || $name == "&lt;$key&gt;" ) {
1596 return $group;
1597 } else {
1598 return $name;
1599 }
1600 }
1601
1602 /**
1603 * Return the set of defined explicit groups.
1604 * The * and 'user' groups are not included.
1605 * @return array
1606 * @static
1607 */
1608 function getAllGroups() {
1609 global $wgGroupPermissions;
1610 return array_diff(
1611 array_keys( $wgGroupPermissions ),
1612 array( '*', 'user' ) );
1613 }
1614
1615 }
1616
1617 ?>